package com.hz.cheetah.server.imp;

import com.hz.cheetah.common.net.NetUtil;
import com.hz.cheetah.server.Session;
import io.netty.channel.socket.SocketChannel;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * Created by yangchuan on 16/7/6.
 */
public class RpcSession implements Session {

    private SocketChannel _sc;
    public long lasttime;
    public volatile int tryitCount;

    public String clientAddress;

    private long sessionID;

    public RpcSession(SocketChannel sc){
        this._sc = sc;
        InetSocketAddress remoteAddress = sc.remoteAddress();
        clientAddress = remoteAddress.toString();
        sessionID = NetUtil.stringIpPort2ServerUID(new String[]{remoteAddress.getHostString(),remoteAddress.getPort()+""});
    }


    @Override
    public void write(Object obj) {
        if (_sc != null) {
            _sc.writeAndFlush(obj);
        }
    }

    @Override
    public void close(Boolean fast) {
        if (_sc != null && _sc.isActive()) {
            _sc.disconnect();
        }
        _sc = null;
    }

    @Override
    public void write(Object obj, SocketAddress address) {
        if (_sc != null) {
            _sc.writeAndFlush(obj);
        }
    }

    @Override
    public long sessionID() {
        return sessionID;
    }


    public void addCount(){
        lasttime = System.currentTimeMillis();
        tryitCount++;
    }

    public void reset(){
        tryitCount = 0;
        lasttime = System.currentTimeMillis();
    }

    public String getClientAddress(){
        return clientAddress;
    }
}
